from enum import unique
from flask import Flask,request
from flask_sqlalchemy import SQLAlchemy
from config import Config
from flask_cors import CORS

app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
cors = CORS(app)

class Orders(db.Model):
    __tablename__='orders'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    name = db.Column(db.String(30),unique=True,default='')
    age = db.Column(db.Integer)

# db.drop_all()
# db.create_all()

import json

@app.route('/list',methods=['POST','GET','PUT','DELETE'])
def list():
    if request.method=='POST':
        data = json.loads(request.data)
        s = Orders(name = data['name'],age=data['age'])
        db.session.add(s)
        db.session.commit()
        return {"code":200}
    elif request.method=='GET':
        s = Orders.query.all()
        list = []
        for i in s:
            dict = {}
            dict['name'] = i.name
            dict['age'] = i.age
            dict['id'] = i.id
            list.append(dict)
        return {'code':200,'list':list}

    elif request.method == 'PUT':
        id = request.args['id']
        age = request.args['age']
        name = request.args['name']
        print(name,age)
        Orders.query.filter_by(id=id).update({'name':name,'age':age})
        db.session.commit()
        return {'code':200}

    elif request.method=='DELETE':
        id = request.args['id']
        Orders.query.filter_by(id=id).delete()
        db.session.commit()
        return {"code":200}
if __name__ == "__main__":
        app.run()